<template>
  <div class="grid gap-6 py-6">
    <template v-if="type==='question'">
      <div v-for="item in list" :key="'article-'+item.id" class="tab-card reply-card group cursor-pointer" @click="handleItemClick(item)">
        <!-- 问题标题/版块 -->
        <div class="flex gap-2 items-center mb-3">
          <div class="flex gap-2 flex-wrap">
            <el-tag
              v-for="(tag, index) in item.specialtyTagNames"
              :key="tag"
              :type="getTagStyle(tag, index).type"
              :class="getTagStyle(tag, index).class"
              size="small"
              class="mr-2"
            >{{ tag }}</el-tag>
          </div>
          <span class="font-bold text-lg text-blue-900">{{ item.title }}</span>
        </div>
        <!-- 作者区 -->
        <div class="flex items-center gap-2 mb-3">
          <img :src="item.avatar || defaultAvatar" class="w-8 h-8 rounded-full object-cover" />
          <span class="font-bold text-slate-800 text-sm">{{ item.username }}</span>
          <span class="text-xs text-slate-400">{{ item.createTime }}</span>
        </div>
        <!-- 内容区 -->
        <div class="flex-1 min-w-0 mb-3">
          <!-- <template v-if="!isExpanded(item.id)">
            <div class="text-slate-700 text-base line-clamp-2 mb-1" v-html="item.content.slice(0, 90)"></div>
            <a v-if="item.content && item.content.length > 90" href="javascript:;" class="text-blue-500 text-xs hover:underline ml-1" @click.stop="expandArticle(item.id)">阅读全文</a>
          </template>
          <template v-else>
            <div class="text-slate-700 text-base mb-1" v-html="item.content"></div>
            <a v-if="item.content && item.content.length > 90" href="javascript:;" class="text-blue-500 text-xs hover:underline ml-1" @click.stop="collapseArticle(item.id)">收起</a>
          </template> -->
          <div class="text-slate-700 text-base mb-1 line-clamp-2" v-html="item.content"></div>

        </div>
        <!-- 数据统计 -->
        <div class="flex items-center gap-4 text-sm text-gray-500">
          <span class="flex items-center gap-1">
            <el-icon><View /></el-icon>
            {{ item.viewCount }} 浏览
          </span>
          <span class="flex items-center gap-1">
            <el-icon><ChatRound /></el-icon>
            {{ item.answerCount }} 回答
          </span>
          <span class="flex items-center gap-1">
            <el-icon><Star /></el-icon>
            {{ item.likeCount }} 点赞
          </span>
        </div>
      </div>
    </template>
    <template v-else-if="type==='answer'">
      <div v-for="item in list" :key="item.id" class="tab-card question-card group cursor-pointer" @click="handleItemClick(item)">
        <div class="flex gap-2 items-center mb-3">
          <div class="flex gap-2 flex-wrap">
            <el-tag
              v-for="(tag, index) in item.specialtyTagNames"
              :key="tag"
              :type="getTagStyle(tag, index).type"
              :class="getTagStyle(tag, index).class"
              size="small"
              class="mr-2"
            >{{ tag }}</el-tag>
          </div>
          <span class="font-bold text-lg text-blue-900">{{ item.title }}</span>
        </div>
        <div class="flex items-center gap-2 mb-3">
          <img :src="item.avatar || defaultAvatar" class="w-8 h-8 rounded-full object-cover" />
          <span class="font-bold text-slate-800 text-sm">{{ item.username }}</span>
          <span class="text-xs text-slate-400">{{ item.createTime }}</span>
        </div>
        <div class="text-slate-700 text-base mb-1 line-clamp-2" v-html="item.content"></div>

        <div class="flex items-center gap-4 text-sm text-gray-500">
          <span>{{ item.createTime }}</span>
          <!-- <span class="flex items-center gap-1">
            <el-icon><View /></el-icon>
            {{ item.viewCount }} 浏览
          </span>
          <span class="flex items-center gap-1">
            <el-icon><ChatRound /></el-icon>
            {{ item.answerCount }} 回答
          </span>
          <span class="flex items-center gap-1">
            <el-icon><Star /></el-icon>
            {{ item.likeCount }} 点赞
          </span> -->
        </div>
      </div>
    </template>
    <template v-else-if="type==='reply'">
      <div v-for="item in list" :key="item.id" class="tab-card reply-card group cursor-pointer" @click="handleItemClick(item)">
        <!-- 问题标题 -->
        <div class="flex gap-2 items-center mb-4">
          <span class="font-bold text-lg text-blue-900">{{ item.questionTitle }}</span>
        </div>
        
        <!-- 通话双方信息 -->
        <div class="flex items-center justify-between mb-4 bg-slate-50 rounded-xl p-4">
          <!-- 发起方 -->
          <div class="flex items-center gap-3">
            <img :src="item.callerAvatar || defaultAvatar" class="w-10 h-10 rounded-full object-cover border-2 border-blue-100" />
            <div class="flex flex-col">
              <span class="font-medium text-slate-800">{{ item.callerName }}</span>
              <span class="text-xs text-slate-500">发起方</span>
            </div>
          </div>
          
          <!-- 通话状态 -->
          <div class="flex flex-col items-center px-4">
            <el-icon class="text-blue-500 text-xl mb-1" v-if="item.callType === 1" :size="20"><Phone /></el-icon>
            <el-icon class="text-blue-500 text-xl mb-1" v-if="item.callType === 2" :size="20"><VideoCamera /></el-icon>
            <!-- <span class="text-xs text-slate-500">{{ item.duration }}秒</span> -->
        </div>
          
          <!-- 接收方 -->
          <div class="flex items-center gap-3">
            <div class="flex flex-col items-end">
              <span class="font-medium text-slate-800">{{ item.calleeName }}</span>
              <span class="text-xs text-slate-500">接收方</span>
            </div>
            <img :src="item.calleeAvatar || defaultAvatar" class="w-10 h-10 rounded-full object-cover border-2 border-blue-100" />
          </div>
        </div>
        
        <!-- 时间信息 -->
        <div class="flex items-center justify-between text-sm text-slate-500">
          <div class="flex items-center gap-4">
            <span class="flex items-center gap-1">
              <el-icon><Timer /></el-icon>
              交流时间：{{ item.startTime }}
            </span>
            <!-- <span class="flex items-center gap-1">
              <el-icon><Timer /></el-icon>
              结束：{{ item.endTime }}
            </span> -->
          </div>
          <el-tag 
            :type="getCallStatusStyle(item.status).type" 
            size="small"
            :class="{'animate-pulse': item.status === 1}"
          >{{ getCallStatusStyle(item.status).text }}</el-tag>
        </div>
      </div>
    </template>
    <template v-else-if="type==='imageText'">
      <div v-for="item in list" :key="item.id" class="tab-card reply-card group cursor-pointer" @click="handleItemClick(item)">
        <!-- 问题标题 -->
        <div class="flex gap-2 items-center mb-4">
          <span class="font-bold text-lg text-blue-900">{{ item.questionTitle }}</span>
        </div>
        
        <!-- 通话双方信息 -->
        <div class="flex items-center justify-between mb-4 bg-slate-50 rounded-xl p-4">
          <!-- 发起方 -->
          <div class="flex items-center gap-3">
            <img :src="item.senderAvatar || defaultAvatar" class="w-10 h-10 rounded-full object-cover border-2 border-blue-100" />
            <div class="flex flex-col">
              <span class="font-medium text-slate-800">{{ item.senderName }}</span>
              <!-- <span class="text-xs text-slate-500">发起方</span> -->
            </div>
          </div>
          
          <!-- 通话状态 -->
          <div class="flex flex-col items-center px-4">
            
            <el-icon class="text-blue-500 text-xl mb-1"><Message /></el-icon>
            <span class="text-xs  text-blue-500">查看详情</span>
          </div>
          
          <!-- 接收方 -->
          <div class="flex items-center gap-3">
            <div class="flex flex-col items-end">
              <span class="font-medium text-slate-800">{{ item.receiverName }}</span>
              <!-- <span class="text-xs text-slate-500">接收方</span> -->
            </div>
            <img :src="item.receiverAvatar || defaultAvatar" class="w-10 h-10 rounded-full object-cover border-2 border-blue-100" />
          </div>
        </div>
        
        <!-- 时间信息 -->
        <div class="flex items-center justify-between text-sm text-slate-500">
          <div class="flex items-center gap-4">
            <span class="flex items-center gap-1">
              <el-icon><Timer /></el-icon>
              交流时间：{{ item.startTime }}
            </span>
            <!-- <span class="flex items-center gap-1">
              <el-icon><Timer /></el-icon>
              结束：{{ item.endTime }}
            </span> -->
          </div>
          <!-- <el-tag 
            :type="getCallStatusStyle(item.status).type" 
            size="small"
            :class="{'animate-pulse': item.status === 1}"
          >{{ getCallStatusStyle(item.status).text }}</el-tag> -->
        </div>
      </div>
    </template>
    <div v-if="!list.length" class="text-center text-slate-400 py-12">暂无相关内容</div>
    <!-- 全局聊天面板 -->
    <el-dialog
      v-model="showGlobalChat"
      title="答疑记录"
      width="520px"
      :close-on-click-modal="false"
      destroy-on-close
      class="global-chat-dialog"
      @close="showGlobalChat = false"
    >
      <div class="chat-container">
        <div class="chat-main">
          <!-- 消息列表 -->
          <div ref="messageListRef" class="message-list">
            <div
              v-for="(message,index) in globalChatMessages"
              :key="message.id"
              class="message-item"
              :class="{ 'self': message.isSelf }"
            >
              <div class="message-content">
                <div class="message-header">
                  <span class="sender-name">{{ message.senderName }}</span>
                  <span class="message-time">{{ message.sendTime}}</span>
                </div>
                <!-- 文本消息 -->
                <div v-if="message.messageType === 0" class="message-text">
                  {{ message.content }}
                </div>
                <!-- 图片消息 -->
                <div v-else-if="message.messageType === 1" class="message-media">
                  <el-image 
                    :src="message.content" 
                    :preview-src-list="[message.content]"
                    fit="cover"
                    class="message-image"
                  >
                    <template #error>
                      <div class="image-error">
                        <el-icon><Picture /></el-icon>
                        <span>加载失败</span>
              </div>
            </template>
                  </el-image>
                </div>
                <!-- 音视频消息 -->
                <div v-else-if="message.msgType === 2" class="message-media">
                  <video 
                    v-if="isVideoFile(message.content)" 
                    controls 
                    class="message-video"
                  >
                    <source :src="message.content" type="video/mp4">
                    您的浏览器不支持视频播放
                  </video>
                  <audio 
                    v-else 
                    controls 
                    class="message-audio"
                  >
                    <source :src="message.content" type="audio/mpeg">
                    您的浏览器不支持音频播放
                  </audio>
                </div>
                <!-- 其他文件消息 -->
                <div v-else-if="message.msgType === 3" class="message-file" @click="handleFileDownload(message.content)">
                  <el-icon><Document /></el-icon>
                  <span class="file-name">{{ getFileName(message.content) }}</span>
                  <el-icon><Download /></el-icon>
                  </div>
              </div>
            </div>
      </div>
        </div>
      </div>
      </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { View, ChatRound, Star, VideoCamera, Timer, Phone,Message } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { get } from '@/axios/utils/request'

const props = defineProps({
  list: Array,
  type: String,
  total: {
    type: Number,
    default: 0
  }
})

const router = useRouter()
const defaultAvatar = 'https://img1.baidu.com/it/u=1618033988,3141592653&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=200'
const showGlobalChat = ref(false)
const globalChatMessages = ref([])

// 标签颜色配置
const tagTypes = [
  { type: '', class: 'tag-blue' },
  { type: 'success', class: 'tag-green' },
  { type: 'warning', class: 'tag-orange' },
  { type: 'danger', class: 'tag-red' },
  { type: 'info', class: 'tag-gray' },
  { type: '', class: 'tag-purple' },
  { type: '', class: 'tag-cyan' },
  { type: '', class: 'tag-pink' }
]

const messageListRef = ref(null)

// 滚动到底部
const scrollToBottom = () => {
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight
  }
}

// 判断是否是视频文件
const isVideoFile = (url) => {
  const videoExtensions = ['.mp4', '.webm', '.ogg']
  return videoExtensions.some(ext => url.toLowerCase().endsWith(ext))
}

// 从URL中获取文件名
const getFileName = (url) => {
  try {
    const urlObj = new URL(url)
    const pathname = urlObj.pathname
    return pathname.substring(pathname.lastIndexOf('/') + 1)
  } catch (error) {
    return url.substring(url.lastIndexOf('/') + 1)
  }
}
// 处理文件下载
const handleFileDownload = (url) => {
  try {
    // 创建一个隐藏的a标签
    const link = document.createElement('a')
    link.href = url
    link.download = getFileName(url) // 设置下载文件名
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('下载文件失败')
  }
}

// 获取标签的类型和自定义类名
function getTagStyle(tag, index) {
  const tagStyle = tagTypes[index % tagTypes.length]
  return {
    type: tagStyle.type,
    class: tagStyle.class
  }
}

// 获取通话状态样式
function getCallStatusStyle(status) {
  switch (status) {
    case 0:
      return {
        type: 'warning',
        text: '未接通'
      }
    case 1:
      return {
        type: 'success',
        text: '通话中'
      }
    case 2:
      return {
        type: 'info',
        text: '已结束'
      }
    case 3:
      return {
        type: 'danger',
        text: '已拒绝'
      }
    default:
      return {
        type: 'info',
        text: '未知状态'
      }
  }
}

// 点击跳转到问题详情
async function handleItemClick(item) {
  if(props.type==='imageText') {
    // 请求聊天记录
    try {
      const res = await get('question/chatmessages', { sessionId: item.id })
      if (res.code === 0 && Array.isArray(res.data)) {
        let data = res.data || []
        let senderId = ''
        data.forEach(item => {
          // item.senderId = item.senderId || item.sender
          if(!senderId) {
            senderId = item.senderId
            item.isSelf = true
          } else {
            if(item.senderId === senderId) {
              item.isSelf = true
            } else {
              item.isSelf = false
            }
          }
        })
        globalChatMessages.value = data
      } else {
        globalChatMessages.value = []
      }
    } catch (e) {
      globalChatMessages.value = []
    }
    showGlobalChat.value = true
    nextTick(() => {
      scrollToBottom()
    })
    return
  } 
   
  if (props.type === 'article' || props.type === 'question' || props.type === 'reply' || props.type === 'answer') {
    router.push(`/question/${item.questionId || item.id}`)
  }
}

// 展开/收起文章内容
const expandedMap = reactive({})
function getKey(id) {
  return `${props.type || ''}_${id}`
}
function isExpanded(id) {
  return !!expandedMap[getKey(id)]
}
function expandArticle(id) {
  expandedMap[getKey(id)] = true
}
function collapseArticle(id) {
  expandedMap[getKey(id)] = false
}
</script>

<style scoped>
.tab-card {
  background: #fff;
  border-radius: 1.2rem;
  box-shadow: 0 1px 6px 0 rgba(56,112,255,0.04);
  padding: 1.5rem 2rem;
  border: 1px solid #f0f3fa;
  transition: all 0.3s ease;
}

.tab-card:hover {
  background: #f6faff;
  border-color: #a3c8fa;
  box-shadow: 0 4px 16px 0 rgba(56,112,255,0.10);
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 自定义标签颜色 */
:deep(.tag-blue) {
  background-color: #e6f4ff;
  border-color: #91caff;
  color: #0958d9;
}

:deep(.tag-green) {
  background-color: #e6fffb;
  border-color: #87e8de;
  color: #08979c;
}

:deep(.tag-orange) {
  background-color: #fff7e6;
  border-color: #ffd591;
  color: #d46b08;
}

:deep(.tag-red) {
  background-color: #fff1f0;
  border-color: #ffa39e;
  color: #cf1322;
}

:deep(.tag-purple) {
  background-color: #f9f0ff;
  border-color: #d3adf7;
  color: #722ed1;
}

:deep(.tag-cyan) {
  background-color: #e6fffb;
  border-color: #87e8de;
  color: #13c2c2;
}

:deep(.tag-pink) {
  background-color: #fff0f6;
  border-color: #ffadd2;
  color: #eb2f96;
}

:deep(.tag-gray) {
  background-color: #fafafa;
  border-color: #d9d9d9;
  color: #666666;
}

/* 标签悬停效果 */
:deep(.el-tag:hover) {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
}

/* 通话中状态的动画效果 */
.animate-pulse {
  animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}

@keyframes pulse {
  0%, 100% {
  opacity: 1;
}
  50% {
    opacity: 0.7;
  }
}
</style> 
